package ma.belsoft.syga.webapp.action;

import java.util.ArrayList;
import java.util.List;

import ma.belsoft.syga.model.Marque;
import ma.belsoft.syga.model.Modele;
import ma.belsoft.syga.service.MarqueManager;
import ma.belsoft.syga.service.ModeleManager;

import com.opensymphony.xwork2.Preparable;

public class ModeleAction extends BaseAction implements Preparable {
    private ModeleManager modeleManager;
    private MarqueManager marqueManager;
    private List modeles;
    private List<Marque> marques = new ArrayList<Marque>();
    private Modele modele;
    private Long id;
    private String query;

    public void setMarqueManager(MarqueManager marqueManager) {
        this.marqueManager = marqueManager;
    }

    public void setModeleManager(ModeleManager modeleManager) {
        this.modeleManager = modeleManager;
    }
    
    public List getModeles() {
        return modeles;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String modeleId = getRequest().getParameter("modele.id");
            if (modeleId != null && !modeleId.equals("")) {
                modele = modeleManager.get(new Long(modeleId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        modeles = modeleManager.search(query, Modele.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Modele getModele() {
        return modele;
    }

    public void setModele(Modele modele) {
        this.modele = modele;
    }

    public String delete() {
        modeleManager.remove(modele.getId());
        saveMessage(getText("modele.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            modele = modeleManager.get(id);
        } else {
            modele = new Modele();
            modele.setMarque(new Marque());
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (modele.getId() == null);

        modeleManager.save(modele);

        String key = (isNew) ? "modele.added" : "modele.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }

	public void setMarques(List<Marque> marques) {
		this.marques = marques;
	}

	public List<Marque> getMarques() {
		return marqueManager.getAll();
	}
}